<?php

define('CURSCRIPT', 'tool');
require_once './core/init.inc.php';
$navtitle.= ' - 工具';

switch($_GET['action']){
case 'import':
	if($_POST){
		if(empty($_FILES['importfile']['name'])){
			showmsg('请选择数据文件再导入。', 'back');
		}

		$info = pathinfo($_FILES['importfile']['name']);
		$info['extension'] = strtolower($info['extension']);
		if($info['extension'] != 'xls' && $info['extension'] != 'xlsx'){
			showmsg('抱歉，文件格式无法识别，仅支持Excel电子表格，请用Excel另存为xls(Excel 2003或更低版本)或xlsx(Excel 2007或更高版本)格式后再上传。', 'back');
		}
	
		$db->select_table('project');
		
		include S_ROOT.'./model/PHPExcel/IOFactory.php';
		$objPHPExcel = PHPExcel_IOFactory::load($_FILES['importfile']['tmp_name']);
		$sheetData = $objPHPExcel->getActiveSheet()->toArray('');
		//0 => '交易日期', 1 => '贷方', 2 => '项目代码', 3 => '项目名称', 4 => '捐赠单位', 5 => '受赠单位', 6 => '项目用途', 7 => '捐赠类型', 8 => '对方户名', 9 => '摘要', 10 => '备注'
		
		unset($sheetData[0]);
		$data = array();
		foreach($sheetData as $row){
			$new = array(
				'creditedtime' => trim($row[0]),
				'amount' => floatval($row[1]),
				'code' => trim($row[2]),
				'name' => trim($row[3]),
				'source' => trim($row[4]),
				'target' => trim($row[5]),
				'specifieduses' => trim($row[6]),
				'sponsortype' => trim($row[7]),
				'sourceaccount' => trim($row[8]),
				//'type' => trim($row[9]),
				//'extra' => $row[10],
			);
			
			if((empty($new['code']) && empty($new['name']) && empty($new['source'])) || $new['amount'] == 0.0){
				continue;
			}
			
			$new['restamount'] = $new['amount'];
			
			$data[] = Project::convertToOriginal($new);
		}

		foreach($data as $node){
			Project::insertItem($node);
		}
		showmsg('导入数据成功！', 'refresh');
	}
break;

case 'export':
	$db->select_table('project');
	
	$projects = array();
	$query = $db->SELECT(array('code','name','responsor','type','dateline','deadline','status','source','amount','restamount','creditedtime','specifieduses'));
	while($p = $db->fetch_array($query)){
		$projects[] = Project::convertToReadable($p);
	}
	
	$csv = new CSVFile();
	$csv->setItem('项目代码,项目名称,项目负责人,项目类型,添加项目时间,项目截止日期,项目状态,捐赠单位,捐赠数额,剩余金额,到账日期,指定用途');
	$csv->importArray($projects);
	$file_content = iconv('utf-8', 'gbk', $csv->exportCsv());
	
	rheader('Content-Encoding: gbk');
	rheader('Cache-Control: no-cache, must-revalidate');
	rheader('Content-Type: application/csv');
	rheader('Content-Disposition: attachment; filename=project_'.rgmdate($_G['timestamp'], 'Ymd').'.csv');
	rheader('Content-Length: '.strlen($file_content));
	echo $file_content;
	exit();
break;
}

include view('tool');

?>